import 'dart:developer';
import 'dart:typed_data';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:developer';
import 'dart:ui' show hashValues;

import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';

class MyImageCache extends ImageCache {
  MyImageCache({this.imageStreamListener});

  final ImageStreamListener imageStreamListener;

  @override
  void clear() {
    super.clear();
  }

  @override
  ImageStreamCompleter putIfAbsent(Object key, ImageStreamCompleter loader(), {ImageErrorListener onError}) {
    ImageStreamCompleter re = super.putIfAbsent(key, loader, onError: onError);
    if (imageStreamListener != null) {
      re.addListener(imageStreamListener);
    }
    return re;
  }
}

class MyWidgetsBinding extends WidgetsFlutterBinding {
  MyWidgetsBinding({this.imageStreamListener});

  final ImageStreamListener imageStreamListener;

  @override
  ImageCache createImageCache() {
    MyImageCache cache = MyImageCache(imageStreamListener: imageStreamListener);
    // cache.maximumSizeBytes = 100 << 20; // 100 MiB = 104857600
    cache.maximumSizeBytes = 52428800; // 50 MiB
    return cache;
  }
}

void main() {
  ImageStreamListener imageStreamListener = ImageStreamListener((ImageInfo imageInfo, bool synchronousCall) async {
    ByteData bd = await imageInfo.image.toByteData();
    print('${DateTime.now().toLocal()} onImage: ${imageInfo.image.width}, ${imageInfo.image.height}, ${bd.lengthInBytes}, ${imageInfo.scale}');
  }, onChunk: (ImageChunkEvent event) {
    print('onChunk: $event');
  }, onError: (Object exception, StackTrace stackTrace) {
    print('onError: $exception');
  });
  MyWidgetsBinding(imageStreamListener: imageStreamListener);
  runApp(MyImageApp());
  // PaintingBinding.instance.imageCache.maximumSize = 100;
  print('@${PaintingBinding.instance.imageCache.maximumSize}');
  print('@${PaintingBinding.instance.imageCache.maximumSizeBytes}');
}

class MyImageApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '图片性能测试',
      home: Scaffold(
        appBar: AppBar(
          title: Text('图片性能测试'),
        ),
        body: ImageContent(),
        backgroundColor: Colors.white,
      ),
    );
  }
}

class ImageContent extends StatefulWidget {
  @override
  _ImageContentState createState() => _ImageContentState();
}

class _ImageContentState extends State<ImageContent> {
  List<String> images = [];

  @override
  void initState() {
    super.initState();
    String baseUrl = 'https://aieducation-download-1251316161.cos.ap-guangzhou.myqcloud.com/test/images/';
    for (int i = 1; i <= 300; i++) {
      images.add('$baseUrl$i.jpg');
    }
    // test();
  }

  Future<void> test() async {
    String baseUrl = 'https://aieducation-download-1251316161.cos.ap-guangzhou.myqcloud.com';
    Uint8List data = (await NetworkAssetBundle(Uri.parse(baseUrl)).load("test/images/1.jpg")).buffer.asUint8List();
    print('111: ${data.length}');
    final ByteData bytes = await rootBundle.load('assets/1.jpg');
    final Uint8List list = bytes.buffer.asUint8List();
    // 1050*1500*x/8=97372   每个像素 x bit
    // 140*146*x/8=17929   每个像素 x bit  x=7.017221135029354
    print(17929 * 8 / 140 / 146);
    print('222: ${list.lengthInBytes}');
    print('000: ${bytes.lengthInBytes}');
    print('333: ${bytes.elementSizeInBytes}');
    print('444: ${bytes.buffer.lengthInBytes}');
    print('555: ${bytes.offsetInBytes}');
  }

  Widget _testColumn() {
    String url = 'assets/1.jpg';
    return ListView(
      children: [
        Container(
          width: 650,
          height: 200,
          child: Image.asset(
            url,
            width: 100,
            height: 100,
            cacheWidth: 100,
            cacheHeight: 100,
            // fit: BoxFit.contain,
          ),
        ),
        SizedBox(
          height: 20.0,
        ),
        // Container(
        //   width: 650,
        //   height: 200,
        //   child: Image.asset(
        //     url,
        //     width: 1050,
        //     height: 1500,
        //     // fit: BoxFit.contain,
        //   ),
        // ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    print('${MediaQuery.of(context).devicePixelRatio}');
    // return Container(
    //   color: Colors.red,
    //   width: 100,
    //   height: 100,
    // );
    return _testColumn();
    return ListView.separated(
      padding: EdgeInsets.zero,
      itemCount: images.length,
      itemBuilder: (context, index) {
        return Container(
          height: 400.0,
          width: 650.0,
          child: Stack(
            children: [
              ImageWidget(
                url: images[index],
              ),
              Container(
                padding: EdgeInsets.all(20.0),
                color: Colors.lightGreenAccent,
                child: Text(
                  '${index + 1}',
                  style: TextStyle(color: Colors.black, fontSize: 30.0),
                ),
              )
            ],
          ),
        );
      },
      separatorBuilder: (_, index) => Container(height: 24.0),
    );
  }
}

class ImageWidget extends StatelessWidget {
  ImageWidget({this.url});

  final String url;

  Widget build1() {
    // 全部
    return CachedNetworkImage(
      imageUrl: url,
      width: 650,
      height: 400,
      fit: BoxFit.contain,
      fadeInDuration: Duration(),
      fadeOutDuration: Duration(),
      placeholder: (context, String url) {
        return PlaceHolderWidget();
      },
      errorWidget: (context, String url, error) {
        return PlaceHolderWidget();
      },
    );
  }

  Widget build2() {
    return CachedNetworkImage(
      imageUrl: url,
      width: 650,
      height: 400,
      memCacheWidth: 650,
      memCacheHeight: 400,
      fit: BoxFit.contain,
      fadeInDuration: Duration(),
      fadeOutDuration: Duration(),
      placeholder: (context, String url) {
        return PlaceHolderWidget();
      },
      errorWidget: (context, String url, error) {
        return PlaceHolderWidget();
      },
    );
  }

  Widget build3() {
    return Image.network(
      url,
      width: 650,
      height: 400,
      fit: BoxFit.contain,
    );
  }

  Widget build4() {
    return Image.asset(
      url,
      // width: 650,
      // height: 400,
      fit: BoxFit.contain,
    );
  }

  @override
  Widget build(BuildContext context) {
    return build4();
  }
}

class PlaceHolderWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 100.0,
      height: 100.0,
      color: Colors.red,
    );
  }
}
